package com.jc.service.addPullProduct;

import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.*;
import com.jc.framework.enums.ImageStatus;
import com.jc.framework.enums.ProductPrice;
import com.jc.framework.enums.Push;
import com.jc.service.api.ProductCheckAdapter;
import com.jc.service.api.product.Image;
import com.jc.service.api.product.Product;
import com.jc.service.api.product.Sku;
import com.jc.service.attribute.AttributeService;
import com.jc.service.attributevalue.AttributeValueService;
import com.jc.service.productattribute.ProductAttributeService;
import com.jc.service.producttype.ProductTypeService;
import com.jc.service.pullproductlog.PullProductLogService;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.supplierproductprice.SupplierProductPriceService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@Service
public class AddPullProductServiceImpl extends ProductCheckAdapter implements AddPullProductService{

    @Autowired
    private SupplierGoodsService supplierGoodsService;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private AttributeValueService attributeValueService;
    @Autowired
    private ProductAttributeService productAttributeService;
    @Autowired
    private SupplierProductPriceService supplierProductPriceService;
    @Autowired
    private SupplierGoodsPictureListService supplierGoodsPictureListService;
    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private PullProductLogService pullProductLogService;
    @Autowired
    private SupplierProductService supplierProductService;

    public Logger getLoger() {
        return LoggerFactory.getLogger(this.getClass());
    }

    @Transactional
    @Override
    public void addPullProductMethod(Product product) {
        try{
            //必填参数校验
            isProNull(product);
            //封装对象
            SupplierGoods supplierGoods = packageObjectGoods(product);
            getLoger().debug("======封装supplierGoods对象 "+ supplierGoods);
            //保存 supplierGoods
            SupplierGoods supplierGoodsQu = new SupplierGoods();
            supplierGoodsQu.setName(product.getName());
            supplierGoodsQu.setSupplierId(Integer.valueOf(product.getSupplierId()));
            supplierGoodsQu.setBrandid(Long.valueOf(product.getBrandid()));
            List<SupplierGoods> supplierGoods1 = supplierGoodsService.queryAll(supplierGoodsQu);
            if (CollectionUtils.isEmpty(supplierGoods1)){
                supplierGoodsService.add(supplierGoods,false);
            }else{
                supplierGoods.setId(supplierGoods1.get(0).getId());
            }
            //保存详情图片
            List<Image> detailImages = product.getDetailImages();
            detailImages.forEach(detailImage->{
                SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
                supplierGoodsPictureList.setGid(supplierGoods.getId());
                supplierGoodsPictureList.setGoodsId(String.valueOf(supplierGoods.getSupplierId()));
                supplierGoodsPictureList.setImageType(2);
                supplierGoodsPictureList.setImagePath(detailImage.getImageUrl());
                supplierGoodsPictureList.setWidth(detailImage.getWidth());
                supplierGoodsPictureList.setHeight(detailImage.getHeight());
                supplierGoodsPictureList.setImageOrder(detailImage.getSort());
                supplierGoodsPictureListService.add(supplierGoodsPictureList,false);
            });

            List<Image> rotationImages = product.getRotationImages();
            rotationImages.forEach(rotationImage->{
                SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
                supplierGoodsPictureList.setGid(supplierGoods.getId());
                supplierGoodsPictureList.setGoodsId(String.valueOf(supplierGoods.getSupplierId()));
                supplierGoodsPictureList.setImageType(1);
                supplierGoodsPictureList.setImagePath(rotationImage.getImageUrl());
                supplierGoodsPictureList.setWidth(rotationImage.getWidth());
                supplierGoodsPictureList.setHeight(rotationImage.getHeight());
                supplierGoodsPictureList.setImageOrder(0);
                supplierGoodsPictureListService.add(supplierGoodsPictureList,false);
            });
            //保存sku
            List<Sku> skus = product.getSkus();
            skus.forEach(sku -> {
                SupplierProduct supplierProduct = new SupplierProduct();
                supplierProduct.setGid(supplierGoods.getId());
                supplierProduct.setProductId(String.valueOf(sku.getProductId()));
                List<SupplierProduct> supplierProducts = supplierProductService.queryAll(supplierProduct);
                if (supplierProducts != null && supplierProducts.size() > 0){
                    return;
                }
                supplierProduct = packageObjectProduct(sku, supplierGoods.getId());
                supplierProductService.add(supplierProduct,false);
                //先查询分类
                String categoryName = product.getCategoryName();
                //信息不全  分类不存在
                super.checkProType(categoryName,supplierProduct.getId(),Long.valueOf(supplierProduct.getProductId()));
                List<Map<String, Object>> attrlist = sku.getAttrlist();
                SupplierProduct finalSupplierProduct = supplierProduct;
                attrlist.forEach(attrSku->{
                    for(String key : attrSku.keySet()){
                        String value = String.valueOf(attrSku.get(key));
                        //根据 key 查询属性id
                        ProAttribute skuAttr = new ProAttribute();
                        skuAttr.setProductAttributeName(key);
                        List<ProAttribute> attributes = attributeService.queryAll(skuAttr);
                        if (attributes != null && attributes.size() > 0){
                            //查询属性值是否存在 不存在新增
                            AttributeValue attributeValue = new AttributeValue();
                            attributeValue.setAttributeValue(value);
                            attributeValue.setAttributeNameId(Long.valueOf(attributes.get(0).getId()));
                            List<AttributeValue> attributeValues = attributeValueService.queryAll(attributeValue);
                            if (CollectionUtils.isEmpty(attributeValues)){
                                //属性值是否存在
                                super.checkProAttributeValue(key,value,finalSupplierProduct.getId(),Long.valueOf(finalSupplierProduct.getProductId()));
                            }else{
                                //保存sku 和attr的关联表
                                ProductAttribute productAttribute = new ProductAttribute();
                                //skuId
                                productAttribute.setProductId(finalSupplierProduct.getId());
                                //属性名称id
                                productAttribute.setAttributeId(attributes.get(0).getId());
                                //属性名称name
                                productAttribute.setAttributeName(attributes.get(0).getProductAttributeName());
                                //属性值
                                productAttribute.setAttributeValue(attributeValue.getAttributeValue());
                                List<ProductAttribute> productAttributes = productAttributeService.queryAll(productAttribute);
                                //存在直接return;
                                if (CollectionUtils.isNotEmpty(productAttributes)){
                                    return;
                                }
                                //创建时间
                                productAttribute.setCreateTime(new Date());
                                productAttributeService.add(productAttribute,false);
                            }
                        }else{
                            //属性不存在
                            super.checkProAttribute(key,finalSupplierProduct.getId(),Long.valueOf(finalSupplierProduct.getProductId()));
                        }
                    }
                });
                //保存对应的价格
                SupplierProductPrice supplierProductPrice = priceCalculation(sku.getHastax(), sku.getTaxCooperatePrice(), sku.getCooperatePrice(), sku.getSalePrice(), sku.getDefaultFreight(), supplierProduct.getId());
                SupplierProductPrice supplierProductPriceQu = new SupplierProductPrice();
                supplierProductPriceQu.setSupplierProductId(supplierProductPrice.getSupplierProductId());
                List<SupplierProductPrice> supplierProductPrices = supplierProductPriceService.queryAll(supplierProductPriceQu);
                if(supplierProductPrices != null && supplierProductPrices.size() > 0){
                    return;
                }
                supplierProductPriceService.add(supplierProductPrice,false);
            });
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     /计算价格
     hastax 是否含税
     taxCooperatePrice 含税价
     cooperatePrice 不含税价
     salePrice 市场价
     defaultFreight 运费 默认为0
     */
    public SupplierProductPrice priceCalculation(Integer hastax , Integer taxCooperatePrice , Integer cooperatePrice , Integer salePrice , Integer freight,Long productId){
        //0 不含税 1 含税
        SupplierProductPrice _supplierProductPrice = new SupplierProductPrice();
        //含税价 分
        _supplierProductPrice.setTaxcooperateprice(taxCooperatePrice);
        //不含税价 分
        _supplierProductPrice.setCooperateprice(cooperatePrice);
        //运费
        if (freight == null){
            freight = ProductPrice.DEFAULTSHIPPINGCOST.getName();
        }
        //成本价
        if (0 == hastax){
            _supplierProductPrice.setCostPrice(cooperatePrice + freight);
        }else{
            _supplierProductPrice.setCostPrice(taxCooperatePrice + freight);
        }
        //市场价是否为空
        if(salePrice == null){
            _supplierProductPrice.setSaleprice(_supplierProductPrice.getCostPrice()+ (1*ProductPrice.MARKETPRICEPERCENTAGE.getName()/100));
        }else{
            _supplierProductPrice.setSaleprice(salePrice);
        }
        int private_cost_price = 0;
        if (hastax == 0) {// 不含税
            private_cost_price = _supplierProductPrice.getCooperateprice()+ freight;
        } else {
            private_cost_price = _supplierProductPrice.getTaxcooperateprice() + freight;
        }
        // 求差价
        int diffPrice = (_supplierProductPrice.getSaleprice()+freight) - private_cost_price;
        if (diffPrice < 0) {
            getLoger().error("严重警告 ,出现负数................................... 产品SKU ID : " + productId);
        }
        int step = diffPrice / 4; // 四个等级，每级的差价
        _supplierProductPrice.setSupplierProductId(Long.valueOf(productId));
        _supplierProductPrice.setMoneyPrice(_supplierProductPrice.getSaleprice());
        _supplierProductPrice.setLeve1Price(private_cost_price + step + step + step);
        _supplierProductPrice.setLeve2Price(private_cost_price + step + step);
        _supplierProductPrice.setLeve3Price(private_cost_price + step);
        _supplierProductPrice.setLeve4Price(private_cost_price);
        _supplierProductPrice.setUnionCostPrice(private_cost_price);
        _supplierProductPrice.setDefaultFreight(freight);
        return _supplierProductPrice;
    }


    public void isProNull(Product pro) throws IllegalAccessException {
        if (StringUtils.isBlank(pro.getName())){
            throw new BaseServiceException("缺少必填参数 : name");
        }
    }

    //封装goods对象
    public SupplierGoods packageObjectGoods(Product pro){
        SupplierGoods supplierGoods = new SupplierGoods();
        //产品名字
        supplierGoods.setName(pro.getName());
        //品牌id
        supplierGoods.setBrandid(Long.valueOf(pro.getBrandid()));
        //品牌中文
        supplierGoods.setBrandnamecn(pro.getBrandnamecn());
        //品牌英文
        supplierGoods.setBrandnameen(pro.getBrandnameen());
        //TODO 一级分类暂时为空
        supplierGoods.setTypeId(null);
        supplierGoods.setTypeName(null);
        //二级分类
        supplierGoods.setCategoryParentId(pro.getCategoryParentId());
        supplierGoods.setCategoryParentName(pro.getCategoryParentName());
        //三级分类
        supplierGoods.setCategoryId(pro.getCategoryId());
        supplierGoods.setCategoryName(pro.getCategoryName());
        //产品详情格式类型 html , pic
        supplierGoods.setGoodsDescType(pro.getGoodsDescType());
        // 这个字段 存储产品介绍详情，如果是图片不从这里取值 ，这里面只存富文本类型
        supplierGoods.setGoodsDesc(pro.getGoodsDesc());
        //供应商系统产品ID，用文本类型为了兼容不同供应商系统
        supplierGoods.setSupplierGoodsId(pro.getSupplierGoodsId());
        //供应商ID
        supplierGoods.setSupplierId(Integer.valueOf(pro.getSupplierId()));
        //供应商名称
        supplierGoods.setSupplierName(pro.getSupplierName());
        //同步时间
        supplierGoods.setCreateTime(new Date());
        //最后更新时间
        supplierGoods.setLastUpdateTime(new Date());
        supplierGoods.setGoodNatureType(pro.getGoodNatureType());
        supplierGoods.setSpecificationsString(pro.getSpecificationsString());
        return supplierGoods;
    }


    public SupplierProduct packageObjectProduct(Sku sku,Long goodsId){
        SupplierProduct supplierProduct = new SupplierProduct();
        supplierProduct.setGid(goodsId);
        //goodsId
        supplierProduct.setGoodsId(sku.getGoodsId());
        //供应商SKU id
        supplierProduct.setProductId(sku.getProductId());
        //供应商SKU name
        supplierProduct.setProductName(sku.getProductName());
        /**
         * SKU规格图片
         */
        supplierProduct.setProductImagePath(sku.getProductImagePath());
        /**
         * 私有云图片地址
         */
        supplierProduct.setSelfProductImagePath(sku.getSelfProductImagePath());
        /**
         * SKU 条码
         */
        supplierProduct.setBarCode(sku.getBarCode());
        /**
         * 是否含税 0 不含税  1 含税
         */
        supplierProduct.setHastax(sku.getHastax());
        /**
         * 供应商产品编码
         */
        supplierProduct.setGoodsId(sku.getGoodsId());
        /**
         * 规格字符串JSON格式
         */
        supplierProduct.setSpecificationsString(sku.getSpecificationsString());
        /**
         * 0 : 不推送
         1 : 待推送
         2 : 已推送
         3 : 推送失败
         */
        supplierProduct.setPushStatus(Push.WAIT_DEAL.getName());
        /**
         * 是否进行图片压缩 0 未压缩 1 已经压缩
         * */
        supplierProduct.setIsImgCompression(ImageStatus.UNCOMPRESSED.getName());
        /**
         * 库存数,同步更新
         */
        supplierProduct.setInventoryNum(sku.getInventoryNum());
        return supplierProduct;
    }
}
